package com.zhuoya.healthcard;

import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.RequiresApi;
import android.support.constraint.ConstraintLayout;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhuoya.healthcard.contants.Contants;
import com.zhuoya.healthcard.util.HttpUtil;
import com.zhuoya.healthcard.util.IdCardUtil;
import com.zhuoya.healthcard.util.ToastUtil;
import com.ldoublem.loadingviewlib.view.LVCircularZoom;
import com.tx.printlib.UsbPrinter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;


public class InputCardNumberActivity extends BaseActity implements View.OnClickListener {

    private TextView mNo1;
    private TextView mNo2;
    private TextView mNo3;
    private ImageButton mDelete;
    private TextView mNo4;
    private TextView mNo5;
    private TextView mNo6;
    private TextView mNoX;
    private TextView mNo7;
    private TextView mNo8;
    private TextView mNo9;
    private TextView mNo0;
    private TextView mConfirm;
    private MyCardNoView mCardNoView;
    private ConstraintLayout mKeyboardView;
    private TextView mNext;
    private LVCircularZoom mProgressBar;
    private LVCircularZoom mLoading;
    private UsbPrinter mUsbPrinter;
    private EditText mName;
    private int pageStatus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_input_card);

        this.pageStatus = this.getIntent().getIntExtra("pageStatus", 2);
        this.initView();
        this.mUsbPrinter = new UsbPrinter(this.getApplicationContext());
    }

    private void initView() {
        this.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            public void onClick(final View view) {
                final InputCardNumberActivity this$0 = InputCardNumberActivity.this;
                this$0.startActivity(new Intent(this$0, MainActivity.class));
                InputCardNumberActivity.this.finish();
            }
        });
        this.findViewById(R.id.backTV).setOnClickListener(new View.OnClickListener() {
            public void onClick(final View view) {
                final InputCardNumberActivity this$0 = InputCardNumberActivity.this;
                this$0.startActivity(new Intent(this$0, MainActivity.class));
                InputCardNumberActivity.this.finish();
            }
        });
        mProgressBar = findViewById(R.id.loading);
        mCardNoView = findViewById(R.id.card_no_view);
        mKeyboardView = findViewById(R.id.keyboard_view);
        mNext = findViewById(R.id.next);
        mNo1 = findViewById(R.id.no_1);
        mNo2 = findViewById(R.id.no_2);
        mNo3 = findViewById(R.id.no_3);
        mDelete = findViewById(R.id.delete);
        mNo4 = findViewById(R.id.no_4);
        mNo5 = findViewById(R.id.no_5);
        mNo6 = findViewById(R.id.no_6);
        mNoX = findViewById(R.id.no_x);
        mNo7 = findViewById(R.id.no_7);
        mNo8 = findViewById(R.id.no_8);
        mNo9 = findViewById(R.id.no_9);
        mNo0 = findViewById(R.id.no_0);
        mConfirm = findViewById(R.id.confirm);

        mName = findViewById(R.id.editText);
        mLoading = findViewById(R.id.loading);

        mNo1.setOnClickListener(this);
        mNo2.setOnClickListener(this);
        mNo3.setOnClickListener(this);
        mNo4.setOnClickListener(this);
        mNo5.setOnClickListener(this);
        mNo6.setOnClickListener(this);
        mNo7.setOnClickListener(this);
        mNo8.setOnClickListener(this);
        mNo9.setOnClickListener(this);
        mNo0.setOnClickListener(this);
        mNoX.setOnClickListener(this);
        mDelete.setOnClickListener(this);
        mConfirm.setOnClickListener(this);
        mCardNoView.setOnClickListener(this);
        mNext.setOnClickListener(this);
        mLoading.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.no_1:
            case R.id.no_2:
            case R.id.no_3:
            case R.id.no_4:
            case R.id.no_5:
            case R.id.no_6:
            case R.id.no_7:
            case R.id.no_8:
            case R.id.no_9:
            case R.id.no_0:
            case R.id.no_x:
                String s = ((TextView) v).getText().toString();
                mCardNoView.inputNum(s);
                break;

            case R.id.delete:
                mCardNoView.deleteNum();
                break;

            case R.id.confirm:
                mNext.setVisibility(View.VISIBLE);
                mKeyboardView.setVisibility(View.GONE);
                break;

            case R.id.card_no_view:
                mNext.setVisibility(View.GONE);
                mKeyboardView.setVisibility(View.VISIBLE);
                break;

            case R.id.next:
                final String content = this.mCardNoView.getContent();
                final String name = this.mName.getText().toString();
                if (content == null || "".equals(content)) {
                    ToastUtil.show(this, "请填写身份证号");
                    return;
                }
                if (!IdCardUtil.validateIdCard18(content)) {
                    ToastUtil.show(this, "身份证号格式错误");
                    return;
                }
                if (name == null || "".equals(name)) {
                    ToastUtil.show(this, "请填写姓名");
                    return;
                }
                if (name.length() > 7) {
                    ToastUtil.show(this, "姓名过长");
                    return;
                }
                final String replaceAll = name.replaceAll("\\s*", "");
                if ("".equals(replaceAll)) {
                    Toast.makeText(this, "请填写姓名", Toast.LENGTH_SHORT).show();
                    return;
                }
                mLoading.setVisibility(View.VISIBLE);
                if (this.mLoading.getVisibility() != View.INVISIBLE) {
                    mLoading.setVisibility(View.INVISIBLE);
                    new Thread(new Runnable() {
                        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                        @Override
                        public void run() {
                            JSONObject param = new JSONObject();
                            param.put("idCard", mCardNoView.getContent());
                            param.put("name", name);
                            param.put("hospitalId", Contants.HOSPITALID);
                            JSONObject resJSON = JSON.parseObject(HttpUtil.submitPostData(Contants.uri + "callNumber/collecTickets", param, "utf-8"));
                            int code = resJSON.getInteger("code").intValue();
                            String msg = resJSON.getString("msg");
                            if (code == 0) {
                                String waitCount = resJSON.getString("waitCount");
                                JSONObject callNumberInfoJSON = resJSON.getJSONObject("callNumberInfo");
                                String number = callNumberInfoJSON.getString("number");
                                String name = callNumberInfoJSON.getString("name");
                                String printInfo = print(name, number, waitCount);
                                if ("8018H".equals(printInfo)) {
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            InputCardNumberActivity.this.startActivity(new Intent(InputCardNumberActivity.this, PrintSuccessActivity.class));
                                            InputCardNumberActivity.this.finish();
                                        }
                                    });
                                } else {
                                    JSONObject errParam = new JSONObject();
                                    errParam.put("hospitalId", Contants.HOSPITALID);
                                    errParam.put("number", number);
                                    errParam.put("name", name);
                                    errParam.put("idCard", mCardNoView.getContent());
                                    HttpUtil.submitPostData(Contants.uri + "callNumber/removeNumber", errParam, "utf-8");
                                    if ("8028H".equals(printInfo)) {
                                        runOnUiThread(new Runnable() {
                                            public void run() {
                                                Intent intent = new Intent(InputCardNumberActivity.this, ErrorActivity.class);
                                                intent.putExtra("errorInfo", "打印机缺纸");
                                                intent.putExtra("code", 3);
                                                intent.putExtra("pageStatus", InputCardNumberActivity.this.pageStatus);
                                                InputCardNumberActivity.this.startActivity(intent);
                                                InputCardNumberActivity.this.finish();
                                            }
                                        });
                                    } else {
                                        runOnUiThread(new Runnable() {
                                            public void run() {
                                                Intent intent = new Intent(InputCardNumberActivity.this, ErrorActivity.class);
                                                intent.putExtra("errorInfo", "打印机错误");
                                                intent.putExtra("code", 3);
                                                intent.putExtra("pageStatus", InputCardNumberActivity.this.pageStatus);
                                                InputCardNumberActivity.this.startActivity(intent);
                                                InputCardNumberActivity.this.finish();
                                            }
                                        });
                                    }
                                }
                            } else if (code == 505) {
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        Intent localIntent = new Intent(InputCardNumberActivity.this, ErrorActivity.class);
                                        localIntent.putExtra("errorInfo", "网络异常");
                                        localIntent.putExtra("code", 4);
                                        localIntent.putExtra("pageStatus", InputCardNumberActivity.this.pageStatus);
                                        InputCardNumberActivity.this.startActivity(localIntent);
                                        InputCardNumberActivity.this.finish();
                                    }
                                });
                            } else {
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        Intent localIntent = new Intent(InputCardNumberActivity.this, ErrorActivity.class);
                                        localIntent.putExtra("errorInfo", "服务器异常");
                                        localIntent.putExtra("pageStatus", InputCardNumberActivity.this.pageStatus);
                                        InputCardNumberActivity.this.startActivity(localIntent);
                                        InputCardNumberActivity.this.finish();
                                    }
                                });
                            }
                        }
                    }).start();
                } else {
                    ToastUtil.show(this, "加载中");
                }

                break;

            default:


        }

    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private UsbDevice getCorrectDevice() {
        final UsbManager usbMgr = (UsbManager) getSystemService(Context.USB_SERVICE);
        final Map<String, UsbDevice> devMap = usbMgr.getDeviceList();
        for (String name : devMap.keySet()) {
            if (UsbPrinter.checkPrinter(devMap.get(name))) {
                final UsbDevice usbDevice = devMap.get(name);
                final String productName = usbDevice.getProductName();
                if (productName != null && " TX PRINTER ".equals(productName)) {
                    return usbDevice;
                }
                continue;
            }
        }
        return null;
    }

    private void hideSoftInput(IBinder binder) {
        if (binder != null)
            ((InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(binder, 2);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    private void showLoading() {
        mProgressBar.setVisibility(View.VISIBLE);
        this.mLoading.setVisibility(View.INVISIBLE);
        mProgressBar.startAnim();
        //模拟请求数据
        new Handler().postDelayed(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void run() {
                JSONObject param = new JSONObject();
                param.put("idCard", mName.getText().toString());
                param.put("name", mCardNoView.getContent());
                param.put("hospitalId", Contants.HOSPITALID);
                JSONObject resJSON = JSON.parseObject(HttpUtil.submitPostData(Contants.uri + "callNumber/collecTickets", param, "utf-8"));
                int code = resJSON.getInteger("code").intValue();
                String msg = resJSON.getString("msg");
                if (code == 0) {
                    String waitCount = resJSON.getString("waitCount");
                    JSONObject callNumberInfoJSON = resJSON.getJSONObject("callNumberInfo");
                    String number = callNumberInfoJSON.getString("number");
                    String name = callNumberInfoJSON.getString("name");
                    String printInfo = print(name, number, waitCount);
                    if ("8018H".equals(printInfo)) {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                InputCardNumberActivity.this.startActivity(new Intent(InputCardNumberActivity.this, PrintSuccessActivity.class));
                                InputCardNumberActivity.this.finish();
                            }
                        });
                    } else {
                        JSONObject errParam = new JSONObject();
                        errParam.put("hospitalId", Integer.valueOf(Contants.HOSPITALID));
                        errParam.put("number", number);
                        errParam.put("name", name);
                        errParam.put("idCard", mCardNoView.getContent());
                        HttpUtil.submitPostData(Contants.uri + "callNumber/removeNumber", errParam, "utf-8");
                        if ("8028H".equals(printInfo)) {
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    Intent intent = new Intent(InputCardNumberActivity.this, ErrorActivity.class);
                                    intent.putExtra("errorInfo", "打印机缺纸");
                                    intent.putExtra("code", 3);
                                    intent.putExtra("pageStatus", InputCardNumberActivity.this.pageStatus);
                                    InputCardNumberActivity.this.startActivity(intent);
                                    InputCardNumberActivity.this.finish();
                                }
                            });
                        } else {
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    Intent intent = new Intent(InputCardNumberActivity.this, ErrorActivity.class);
                                    intent.putExtra("errorInfo", "打印机错误");
                                    intent.putExtra("code", 3);
                                    intent.putExtra("pageStatus", InputCardNumberActivity.this.pageStatus);
                                    InputCardNumberActivity.this.startActivity(intent);
                                    InputCardNumberActivity.this.finish();
                                }
                            });
                        }
                    }
                } else if (code == 505) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Intent localIntent = new Intent(InputCardNumberActivity.this, ErrorActivity.class);
                            localIntent.putExtra("errorInfo", "网络异常");
                            localIntent.putExtra("code", 4);
                            localIntent.putExtra("pageStatus", InputCardNumberActivity.this.pageStatus);
                            InputCardNumberActivity.this.startActivity(localIntent);
                            InputCardNumberActivity.this.finish();
                        }
                    });
                } else {
                    InputCardNumberActivity.this.runOnUiThread(new Runnable() {
                        public void run() {
                            Intent localIntent = new Intent(InputCardNumberActivity.this, ErrorActivity.class);
                            localIntent.putExtra("errorInfo", "服务器异常");
                            localIntent.putExtra("pageStatus", InputCardNumberActivity.this.pageStatus);
                            InputCardNumberActivity.this.startActivity(localIntent);
                            InputCardNumberActivity.this.finish();
                        }
                    });
                }
            }
        }, 5000);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public String print(final String name, final String number, final String waitCount) {
        final UsbDevice correctDevice = this.getCorrectDevice();
        if (correctDevice == null || !this.mUsbPrinter.open(correctDevice)) {
            return "null";
        }
        this.mUsbPrinter.init();
        final String format = String.format("%04XH", this.mUsbPrinter.getStatus2());
        if ("8018H".equals(format)) {
            this.mUsbPrinter.doFunction(7, 1, 0);
            this.mUsbPrinter.doFunction(1, 2, 1);
            this.mUsbPrinter.doFunction(11, 1, 0);
            this.mUsbPrinter.doFunction(13, 15, 0);
            this.mUsbPrinter.outputStringLn("健康证办理");
            this.mUsbPrinter.newline();
            this.mUsbPrinter.resetFont();
            this.mUsbPrinter.doFunction(7, 1, 0);
            this.mUsbPrinter.doFunction(1, 1, 1);
            this.mUsbPrinter.doFunction(11, 1, 0);
            this.mUsbPrinter.doFunction(13, 22, 0);
            final UsbPrinter mUsbPrinter = this.mUsbPrinter;
            final StringBuilder sb = new StringBuilder();
            sb.append("姓名：");
            sb.append(name);
            mUsbPrinter.outputStringLn(sb.toString());
            this.mUsbPrinter.doFunction(7, 1, 0);
            this.mUsbPrinter.newline();
            this.mUsbPrinter.doFunction(1, 1, 1);
            this.mUsbPrinter.doFunction(11, 1, 0);
            this.mUsbPrinter.doFunction(13, 22, 0);
            final UsbPrinter mUsbPrinter2 = this.mUsbPrinter;
            final StringBuilder sb2 = new StringBuilder();
            sb2.append("编号：");
            sb2.append(number);
            mUsbPrinter2.outputStringLn(sb2.toString());
            this.mUsbPrinter.newline();
            this.mUsbPrinter.doFunction(1, 1, 1);
            this.mUsbPrinter.doFunction(11, 1, 0);
            this.mUsbPrinter.doFunction(13, 22, 0);
            final UsbPrinter mUsbPrinter3 = this.mUsbPrinter;
            final StringBuilder sb3 = new StringBuilder();
            sb3.append("等待人数：");
            sb3.append(waitCount);
            mUsbPrinter3.outputStringLn(sb3.toString());
            this.mUsbPrinter.newline();
            this.mUsbPrinter.doFunction(1, 0, 0);
            this.mUsbPrinter.doFunction(11, 1, 0);
            this.mUsbPrinter.doFunction(13, 15, 0);
            final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            final UsbPrinter mUsbPrinter4 = this.mUsbPrinter;
            final StringBuilder sb4 = new StringBuilder();
            sb4.append("当前时间：");
            sb4.append(simpleDateFormat.format(new Date()));
            mUsbPrinter4.outputStringLn(sb4.toString());
            this.mUsbPrinter.doFunction(12, 0, 0);
            this.mUsbPrinter.close();
            return format;
        }
        return format;
    }
}
